package com.wanwanbookstore.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.wanwanbookstore.dao.BookDAO;
import com.wanwanbookstore.dao.CartDAO;
import com.wanwanbookstore.dao.OrderDAO;
import com.wanwanbookstore.entity.CartItem;
import com.wanwanbookstore.entity.OrderItem;
import com.wanwanbookstore.entity.User;
import com.wanwanbookstore.utils.DBUtil;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

public class CheckoutServlet extends HttpServlet {
    private CartDAO cartDAO = new CartDAO();
    private OrderDAO orderDAO = new OrderDAO();
    private BookDAO bookDAO = new BookDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 检查是否是直接购买模式
        CartItem directBuyItem = (CartItem) session.getAttribute("directBuyItem");
        List<CartItem> itemsToCheckout;
        double totalPrice = 0;

        if (directBuyItem != null) {
            // 直接购买模式
            itemsToCheckout = new ArrayList<>();
            itemsToCheckout.add(directBuyItem);
            
            // 检查库存和有效性
            if (directBuyItem.getBook() == null || directBuyItem.getBook().isDeleted()) {
                request.setAttribute("error", "商品已下架");
                // 清除无效的直接购买项
                session.removeAttribute("directBuyItem");
                // 获取来源页面或返回首页
                String referer = request.getHeader("Referer");
                if (referer != null && !referer.isEmpty()) {
                    response.sendRedirect(referer);
                } else {
                    response.sendRedirect("index.jsp");
                }
                return;
            }
            
            if (directBuyItem.getBook().getStock() < directBuyItem.getQuantity()) {
                request.setAttribute("error", "库存不足: " + directBuyItem.getBook().getTitle());
                // 清除无效的直接购买项
                session.removeAttribute("directBuyItem");
                // 获取来源页面或返回首页
                String referer = request.getHeader("Referer");
                if (referer != null && !referer.isEmpty()) {
                    response.sendRedirect(referer);
                } else {
                    response.sendRedirect("index.jsp");
                }
                return;
            }
            
            totalPrice = directBuyItem.getTotalPrice();
            // 设置标志表示使用直接购买模式
            session.setAttribute("useDirectBuy", true);
        } else {
            // 购物车模式
            itemsToCheckout = cartDAO.getCartByUserId(user.getId());
            if (itemsToCheckout.isEmpty()) {
                response.sendRedirect("cart");
                return;
            }

            // 计算总价并检查库存
            boolean hasStock = true;
            StringBuilder stockError = new StringBuilder();

            for (CartItem item : itemsToCheckout) {
                if (item.getBook() == null || item.getBook().isDeleted()) {
                    stockError.append("商品已下架: ").append(item.getBookId()).append("<br>");
                    hasStock = false;
                    continue;
                }
                if (item.getBook().getStock() < item.getQuantity()) {
                    stockError.append("库存不足: ").append(item.getBook().getTitle()).append("<br>");
                    hasStock = false;
                }
                totalPrice += item.getTotalPrice();
            }

            if (!hasStock) {
                request.setAttribute("error", stockError.toString());
                request.getRequestDispatcher("cart.jsp").forward(request, response);
                return;
            }
            
            // 设置标志表示使用购物车模式
            session.setAttribute("useDirectBuy", false);
        }

        request.setAttribute("cartItems", itemsToCheckout);
        request.setAttribute("totalPrice", totalPrice);
        request.setAttribute("user", user);

        request.getRequestDispatcher("checkout.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 获取收货信息
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");

        if (address == null || address.trim().isEmpty() || phone == null || phone.trim().isEmpty()) {
            request.setAttribute("error", "请填写完整的收货信息");
            request.getRequestDispatcher("checkout.jsp").forward(request, response);
            return;
        }

        // 检查是否是直接购买模式
        Boolean useDirectBuy = (Boolean) session.getAttribute("useDirectBuy");
        List<CartItem> itemsToProcess;
        boolean isDirectBuy = useDirectBuy != null && useDirectBuy;

        if (isDirectBuy) {
            // 直接购买模式
            CartItem directBuyItem = (CartItem) session.getAttribute("directBuyItem");
            if (directBuyItem == null) {
                request.setAttribute("error", "商品信息丢失，请重新选择商品");
                response.sendRedirect("index.jsp");
                return;
            }
            
            itemsToProcess = new ArrayList<>();
            itemsToProcess.add(directBuyItem);
        } else {
            // 购物车模式
            itemsToProcess = cartDAO.getCartByUserId(user.getId());
            if (itemsToProcess == null || itemsToProcess.isEmpty()) {
                request.setAttribute("error", "购物车为空，无法提交订单");
                response.sendRedirect("cart");
                return;
            }
        }

        // 检查商品有效性并创建订单项
        List<OrderItem> orderItems = new ArrayList<>();
        double totalPrice = 0;
        StringBuilder invalidItems = new StringBuilder();
        boolean hasValidItems = false;

        for (CartItem item : itemsToProcess) {
            // 确保商品信息完整
            if (item.getBook() == null) {
                invalidItems.append("商品信息缺失: ID=").append(item.getBookId()).append("<br>");
                continue;
            }
            
            // 检查商品是否已下架
            if (item.getBook().isDeleted()) {
                invalidItems.append("商品已下架: ").append(item.getBook().getTitle()).append("<br>");
                continue;
            }
            
            // 检查库存
            if (item.getBook().getStock() < item.getQuantity()) {
                invalidItems.append("库存不足: ").append(item.getBook().getTitle())
                           .append(" (当前库存: " + item.getBook().getStock() + ")<br>");
                continue;
            }
            
            // 创建有效订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setBookId(item.getBookId());
            orderItem.setQuantity(item.getQuantity());
            orderItem.setPrice(item.getBook().getPrice());
            orderItems.add(orderItem);
            totalPrice += item.getTotalPrice();
            hasValidItems = true;
        }

        // 检查是否有有效商品
        if (!hasValidItems) {
            request.setAttribute("error", "没有可购买的有效商品: <br>" + invalidItems.toString());
            // 如果是直接购买模式，清除session中的相关信息
            if (isDirectBuy) {
                session.removeAttribute("directBuyItem");
                session.removeAttribute("useDirectBuy");
            }
            request.getRequestDispatcher("checkout.jsp").forward(request, response);
            return;
        }

        // 如果有部分无效商品，显示警告但继续处理有效商品
        if (invalidItems.length() > 0) {
            request.setAttribute("warning", "以下商品无法购买: <br>" + invalidItems.toString());
        }

        // 使用简化的订单创建方式，避免复杂的事务处理
        Connection conn = null;
        PreparedStatement stmt = null;
        
        try {
            // 获取数据库连接并开启事务
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);
            
            // 生成订单ID：时间戳+随机数
            String orderIdStr = "ORDER" + System.currentTimeMillis() + (int)(Math.random() * 1000);
            
            // 1. 创建订单
            String orderSql = "INSERT INTO orders (id, user_id, total_price, status, create_time, address, phone) VALUES (?, ?, ?, ?, ?, ?, ?)";
            stmt = conn.prepareStatement(orderSql);
            stmt.setString(1, orderIdStr);
            stmt.setInt(2, user.getId());
            stmt.setDouble(3, totalPrice);
            stmt.setString(4, "待发货");
            stmt.setTimestamp(5, new Timestamp(new Date().getTime()));
            stmt.setString(6, address.trim());
            stmt.setString(7, phone.trim());
            stmt.executeUpdate();
            stmt.close();
            
            // 2. 创建订单项
            String itemSql = "INSERT INTO order_item (order_id, book_id, quantity, price) VALUES (?, ?, ?, ?)";
            stmt = conn.prepareStatement(itemSql);
            
            for (OrderItem item : orderItems) {
                stmt.setString(1, orderIdStr);
                stmt.setInt(2, item.getBookId());
                stmt.setInt(3, item.getQuantity());
                stmt.setDouble(4, item.getPrice());
                stmt.executeUpdate();
                
                // 3. 更新库存
                String updateStockSql = "UPDATE book SET stock = stock - ? WHERE id = ? AND stock >= ?";
                PreparedStatement stockStmt = conn.prepareStatement(updateStockSql);
                stockStmt.setInt(1, item.getQuantity());
                stockStmt.setInt(2, item.getBookId());
                stockStmt.setInt(3, item.getQuantity());
                
                int rowsAffected = stockStmt.executeUpdate();
                stockStmt.close();
                
                if (rowsAffected <= 0) {
                    throw new SQLException("库存更新失败，图书ID: " + item.getBookId());
                }
            }
            
            // 提交事务
            conn.commit();
            
            // 4. 根据模式决定是否清空购物车
            if (!isDirectBuy) {
                // 购物车模式下清空购物车
                String clearCartSql = "DELETE FROM cart_item WHERE user_id = ?";
                stmt = conn.prepareStatement(clearCartSql);
                stmt.setInt(1, user.getId());
                stmt.executeUpdate();
            }
            
            // 无论哪种模式，都清除直接购买相关的session属性
            session.removeAttribute("directBuyItem");
            session.removeAttribute("useDirectBuy");
            
            // 跳转到订单成功页面
            response.sendRedirect("order?action=success&id=" + orderIdStr);
            
        } catch (SQLException e) {
            // 回滚事务
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            
            // 记录异常信息
            e.printStackTrace();
            request.setAttribute("error", "订单创建失败: " + e.getMessage());
            request.getRequestDispatcher("checkout.jsp").forward(request, response);
            
        } finally {
            // 关闭连接
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}